public class BinarySearchtTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

    }
    public static TreeNode root=null ;
    //插入语句
    public  boolean insert(int vall) {
        if (root==null){
            root=new TreeNode(vall);
            return true;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (cur.val < vall) {
                parent = cur;
                cur = cur.right;
            }
            else if (cur.val > vall) {
                parent = cur;
                cur = cur.left;
            } else {
                throw new Exception();
            }
        }
        if(parent.val>vall){
            parent.left=new TreeNode(vall);
        }
        if(parent.val<vall){
            parent.right=new TreeNode(vall);
        }
        return true;
    }

    public  boolean search(int vall) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val > vall) {
                cur = cur.left;
            }
            if(cur.val<vall){
                cur=cur.right;
            }
            else {
                return true;
            }

        }
        return false;


    }
    //删除操作
    public void remove(int vall){
        TreeNode cur=root;
        TreeNode parent=null;
        //寻找需要的节点
        while (cur!=null){
            if(vall<cur.val){
                parent=cur;
                cur=cur.left;
            }
            else if(vall>cur.val){
                parent=cur;
                cur=cur.right;
            }
            //找到了节点
            else {
                removendoe(parent,cur);


            }
        }




    }
    private void removendoe(TreeNode parent,TreeNode cur){

        if(cur.left==null){
            //如果节点是根节点
            if(cur==root){
                root=cur.right;
            } else if (cur==parent.right) {
                parent.right=cur.right;
            } else if (cur==parent.left) {
                parent.left=cur.right;
            }


        } else if (cur.right==null) {
            if(cur==root){
                root=cur.left;
            } else if (parent.left==cur) {
                parent.left=cur.left;
            } else if (parent.right==cur) {
                parent.right=cur.left;
            }

        }
        //左右都不为空
        else {
            TreeNode target=cur.right;
            TreeNode targetparent=cur;
            while (target.left!=null){
                targetparent=target;
                target=target.left;
            }
            cur.val=target.val;
            if(target==targetparent.right){
                targetparent.right=target.right;
            }
            else {
                targetparent.left = target.right;
            }
        }

    }


}